/**
 * Created with JetBrains WebStorm.
 * User: Tung An
 * Date: 8/11/13
 * Time: 9:35 AM
 * To change this template use File | Settings | File Templates.
 */

var listTag = [];

var LookManager = {

    init: function () {
        this.show();
        if (xmlUtils.getURLParameter("edit") == "true") {
            this.getLookDetail();
            $id("submit-button").innerText = "Update";
        }
    },

    onClick: function (event) {
        switch (event.target.data) {
            case "img":
                if (this.oldNode)
                    this.oldNode.remove();
                if (this.editNode)
                    this.editNode.remove();
                this.createTag(event);
                break;
            case "tagNode":
                this.createTagNode(event.target.innerText);
                if (this.editNode)
                    this.editNode.remove();
                this.editTag(event.target.innerText);
                event.target.remove();
                break;
            case "create":
                var node = getParentNode(event.target, "tag");
                var tagObj = xmlUtils.getValue(node);
                tagObj.left = node.offsetLeft;
                tagObj.top = node.offsetTop;

                for (var index = 0; index < listTag.length; index++) {
                    if (listTag[index].tagIndex === tagObj.tagIndex) {
                        listTag[index] = tagObj;
                        tagObj = null;
                        break;
                    }
                }
                if (tagObj)
                    listTag.push(tagObj);
                this.createTagNode();
                break;
            case "close":
                var node = event.target.parentNode.parentNode;
                if (hasClass(node, "edit"))
                    this.createTagNode();
                else
                    node.remove();
                break;
            case "delete":
                node = event.target.parentNode.parentNode;
                this.deleteTag(node.children[0].innerText);
                node.remove();
                break;
            case "submit" :
                var node = event.target.parentNode.parentNode;
                var obj = xmlUtils.getValue(node.children[0]);
                this.createLook(obj);
                break;
            case "productImageUpload":
                var node = getParentNode(event.target, "tag-image");
                UploadManager.uploadListener(node);
                break;
            case "delete-image":
                var node = getParentNode(event.target, "tag-image");
                node.getElementsByClassName("image-wrapper")[0].innerHTML = "";
                break;
            default:
                break;
        }
    },

    addListeners: function (node) {
        var self = this;
        node.addEventListener('mousedown', mouseDown, false);
        document.addEventListener('mouseup', mouseUp, false);

        function mouseUp() {
            node.parentElement.children[1].style.opacity = 1;
            document.removeEventListener('mousemove', divMove, true);
        };

        function mouseDown(event) {
            document.addEventListener('mousemove', divMove, true);
        };

        function divMove(event) {
            if (event.target.getAttribute("name") === "category")
                return;
            node.parentElement.style.left = (event.clientX - $id('image-container').offsetLeft - $id('image-look').offsetLeft) + "px";
            node.parentElement.style.top = (event.clientY + document.body.scrollTop - $id('image-container').offsetTop + 15) + "px";
            node.parentElement.children[1].style.opacity = 0;
        }
    },

    createTagNode: function (pos) {
        if (!(listTag.length > 0))
            return;
        $id("tag-container").innerHTML = "";
        listTag.forEach(function (item, index) {
            if (index !== (pos - 1)) {
                var node = $id("tag-node").cloneNode(true);
                node.id = "tag-node-"+item.tagIndex;
                node.style.left = item.left + "px";
                node.style.top = item.top - 20 + "px";
                node.innerText = item.tagIndex;
                $id("tag-container").appendChild(node);
            }
        });
    },

    createTag: function (event) {
        var node = $id("tag-template").cloneNode(true);
        node.children[0].innerText = listTag.length + 1;
        node.id = "tag-detail-" + listTag.length + 1;
        node.style.left = (event.clientX - $id('image-container').offsetLeft - $id('image-look').offsetLeft) + "px";
        node.style.top = (event.clientY + document.body.scrollTop - $id('image-container').offsetTop + 10) + "px";
        $id("tag-container").appendChild(node);
        this.oldNode = node;
        this.addListeners(node.children[0]);
    },

    editTag: function (tagIndex) {
        var editObj = listTag[tagIndex - 1];
        var node = $id("tag-template").cloneNode(true);
        node.id = "tag-detail-" + tagIndex;
        addClass(node, "edit");
        node.getElementsByClassName("image-wrapper")[0].innerHTML = "<img name='tagImage' src/>";
        node.style.left = editObj.left + "px";
        node.style.top = editObj.top + "px";
        xmlUtils.setValue(node, editObj);
        if (editObj.tagImage && editObj.tagImage != "") {
            removeClass(node.getElementsByClassName("delete-image")[0], "hidden");
        } else {
            addClass(node.getElementsByClassName("delete-image")[0], "hidden");
        }
        $id("tag-container").appendChild(node);
        this.editNode = node;
        this.addListeners(node.children[0]);
    },

    deleteTag: function (tagIndex) {
        listTag.forEach(function (tag, index) {
            if (tag.tagIndex == tagIndex) {
                listTag.splice(index, 1);
            }
        });

        listTag.forEach(function (tag, index) {
            tag.tagIndex = index + 1;
        });

        this.createTagNode();
    },

    createLook: function (obj) {

        if (!$class("username")[0] || !$class("username")[0].id) {
            return LoginPopup.init();
        }

        if (xmlUtils.getURLParameter("edit") == "true") {
            obj.lookId = xmlUtils.getURLParameter("look");
        }

        obj.userId = $class("username")[0].id;
        obj.username = "";
        obj.avatarurl = "";
        obj.address = "";
        obj.lookImage = $id("image-look").children[0].src;
        obj.updateTime = "";
        obj.listTag = listTag;
        var xmlDom = xmlUtils.objToXML(obj, "look");

        var success = function (resp) {
            var cb = function () {
                window.location = "/";
            }
            xmlUtils.showTimeOutPopup("Your look has been updated!", null, cb);
        };

        var failure = function () {

        };

        ajax.post({
            url: "ProcessServlet",
            param: {action: "create"},
            xml: xmlDom,
            success: success,
            failure: failure
        });
    },

    getLookDetail: function () {
        var success = function (resp) {
            var LookModel = LookManager.createLookModel(xmlUtils.XMLtoObj(resp).look);
            if (!$class("username")[0] || LookModel.userID != $class("username")[0].id) {
                window.location = "/";
                return;
            }
            listTag = JSON.parse(JSON.stringify(LookModel.listTag));
            xmlUtils.setValue($id("create-look"), LookModel);
            LookManager.createTagNode();
        };

        var failure = function () {
        };

        ajax.post({
            url: "ProcessServlet",
            param: {action: "getlookdetail", lookId: xmlUtils.getURLParameter("look")},
            success: success,
            failure: failure
        });
    },

    createLookModel: function (dto) {
        var LookModel = {};
        LookModel.userID = dto.userid;
        LookModel.username = dto.username;
        LookModel.avatarURL = dto.avatarurl;
        LookModel.address = dto.address;
        LookModel.lookName = dto.lookname;
        LookModel.lookDescription = dto.lookdescription;
        LookModel.lookID = dto.lookid;
        LookModel.lookImage = dto.lookimage;
        LookModel.updateTime = dto.updatetime;

        var listTag = [];
        if (dto.listtag.tag instanceof Array) {
            dto.listtag.tag.forEach(function (tag) {
                var tag = {
                    tagIndex: tag.tagindex,
                    tagName: tag.tagname,
                    tagBrand: tag.tagbrand,
                    tagStore: tag.tagstore,
                    tagStoreUrl: tag.tagstoreurl,
                    tagImage: tag.tagimage,
                    category: tag.category,
                    left: tag.left,
                    top: tag.top
                };
                listTag.push(tag);
            });
        } else if (dto.listtag.tag instanceof Object) {
            var tagObj = dto.listtag.tag;
            var tag = {
                tagIndex: tagObj.tagindex,
                tagName: tagObj.tagname,
                tagBrand: tagObj.tagbrand,
                tagStore: tagObj.tagstore,
                tagStoreUrl: tagObj.tagstoreurl,
                tagImage: tagObj.tagimage,
                category: tagObj.category,
                left: tagObj.left,
                top: tagObj.top
            };
            listTag.push(tag);
        }
        LookModel.listTag = listTag;
        return LookModel;
    },

    show: function () {
        var listener = function (event) {
            var node = event.target;
            event.target.data = xmlUtils.getNodeWithData(node);
            LookManager.onClick(event);
        };
        $id("create-look").addEventListener("click", listener, false);
    }
};

var onload = function () {
    if ($id("main-page")) {
        MainPage.init();
    } else if ($id("create-look")) {
        LookManager.init();
    } else if ($id("upload-page")) {
        UploadManager.init();
    } else if ($id("look-detail")) {
        LookDetail.init();
    } else if ($id("manage-page")) {
        ManagerLook.init();
    }

    if ($id("header")) {
        Header.init()
    }
};

function ready(event) {
    console.log('The DOM is ready.');
    onload();
    window.removeEventListener('DOMContentLoaded', ready);
}
window.addEventListener('DOMContentLoaded', ready);